<?php
namespace app\api\controller;

use cmf\controller\PluginController;
use think\Controller;
use think\View;

/**
 *
 */
class ApiModuleRouteController extends Controller
{
    /**
     * 模块路由
     */
    public function index($index)
    {
        $debugstr = APP_DEBUG ? ' [LOCATION: Route resolution]' : '';
        if (empty($index)) {
            exit('Request resource does not exist' . $debugstr);
        }
        $key = str_replace('_', '/', $index);

        $_plugin     = $index;
        $_controller = $index;
        $_action     = $index;
        $route       = $this->getConfig($key);
        if (false !== $route && !empty($route['addr'])) {

            if (!$this->requestIsOk($route['method'])) {
                //请求类型被拒绝
                exit('The request type is rejected' . $debugstr);
            }

            $tmp = explode('/', $route['addr'], 3);
            if (count($tmp) == 2) {
                $_plugin                     = $route['module'];
                list($_controller, $_action) = $tmp;
            } elseif (count($tmp) == 3) {
                list($_plugin, $_controller, $_action) = $tmp;
            }
        }
        $vars = [
            "_plugin"     => $_plugin,
            "_controller" => $_controller,
            "_action"     => $_action,
        ];

        $reCalss = "\\plugins\\$_plugin\\controller\\" . cmf_parse_name($_controller, 1) . "Controller";
        if (!class_exists($reCalss)) {
            exit('Invalid request address' . $debugstr);
        }

        $this->request->setParam($vars);
        $base = $this->request->root();
        $base .= '/plugins/' . cmf_parse_name($_plugin) . '/' . cmf_parse_name($_controller);

        $this->view->config('view_path', $base);
        $this->view->replace('__URL__', $base);
        //dump($this->view);exit;
        $plugin = new PluginController();
        return $plugin->index($_plugin, $_controller, $_action);
    }

    /**
     * 获取模块路由配置
     */
    public function getModuleRouteConfig()
    {
        header("Content-Type: text/html;charset=utf-8");
        $index      = new \app\admin\controller\IndexController();
        $configList = $this->getConfig();
        echo '<h3>模块路由配置表:<span style="color:red;font-size:14px;">(注:var值具有唯一性,如无法访问到正确的地址,请检查此值是否重复!)</span></h3>';
        dump($configList);exit;
    }

    private function getConfig($index = "")
    {
        $configList = [];
        $find       = false;
        $files      = scandir(PLUGINS_PATH);
        foreach ($files as $key => $name) {
            if ($name == '.' || $name == '..') {
                continue;
            }

            $fileName = PLUGINS_PATH . $name . DS . 'route.php';
            if (file_exists($fileName)) {
                $content = include $fileName;
                if (!is_array($content) || empty($content)) {
                    continue;
                }

                foreach ($content as $rk => $rv) {
                    if (empty($rk) || empty($rv)) {
                        continue;
                    }

                    if ($index != '' && $rk == $index && is_array($rv)) {
                        $find['module']  = $name;
                        $find['addr']    = isset($rv[0]) ? $rv[0] : '';
                        $find['method']  = isset($rv[1]) ? $rv[1] : 'ANY';
                        $find['explain'] = isset($rv[2]) ? $rv[2] : '';
                        break;
                    }
                    $tmp['module']             = $name;
                    $tmp['var']                = str_replace('/', '_', $rk);
                    $tmp['addr']               = isset($rv[0]) ? $rv[0] : '';
                    $tmp['explain']            = isset($rv[1]) ? $rv[1] : '';
                    $tmp['method']             = isset($rv[2]) ? $rv[2] : 'ANY';
                    $configList[$tmp['var']][] = $tmp;
                }
            }
            if (false !== $find) {
                break;
            }
        }
        if (empty($index)) {
            return $configList;
        }
        return $find;
    }

    /**
     * 请求类型
     */
    private function requestIsOk($method = 'any')
    {
        $method     = strtolower($method);
        $methodIsOk = false;
        switch ($method) {
            case 'get':
                $methodIsOk = $this->request->isGet();
                break;
            case 'post':
                $methodIsOk = $this->request->isPost();
                break;
            case 'put':
                $methodIsOk = $this->request->isPut();
                break;
            case 'delete':
                $methodIsOk = $this->request->isDelete();
                break;
            case 'ajax':
                $methodIsOk = $this->request->isAjax();
                break;
            case 'pjax':
                $methodIsOk = $this->request->isPjax();
                break;
            case 'head':
                $methodIsOk = $this->request->isHead();
                break;
            case 'patch':
                $methodIsOk = $this->request->isPatch();
                break;
            case 'options':
                $methodIsOk = $this->request->isOptions();
                break;
            case 'cli':
                $methodIsOk = $this->request->isCli();
                break;
            case 'cgi':
                $methodIsOk = $this->request->isCgi();
                break;
            case 'any':
                $methodIsOk = true;
                break;
            default:
                $methodIsOk = false;
                break;
        }
        return $methodIsOk;
    }
}
